package com.acme.bankapp.service;

import java.io.*;

import com.acme.bankapp.domain.*;
import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.exceptions.NotEnoughFundsException;
import com.acme.bankapp.exceptions.SavingDataFailure;


public class BankService {
	static public void addClient(Bank bank, Client client) throws ClientExistsException, SavingDataFailure{
		bank.addClient(client);
		BankService.saveBank(bank, "saving.txt");
	}
	
	public static void modifyBank(Bank bank, double amount) throws NotEnoughFundsException {
		Client[] clis = bank.getClients();
		int num = bank.getNumberOfClients();
		
		for (int i = 0; i < num; i++) {
			Account[] accs = clis[i].getAccounts();
			int num1 = clis[i].getNumberOfAccounts();
			for (int j = 0; j < num1; j++) {
				accs[j].withdraw(amount);
				accs[j].deposit(amount);
			}
		}
	}
	
	public static void printBalance(Bank bank) {
		Client[] clis = bank.getClients();
		int num = bank.getNumberOfClients();
		
		for (int i = 0; i < num; i++) {
			System.out.println(clis[i]);
		}
	}
	
	public static void printMaximumAmountToWithdraw(Bank bank) {
		Client[] clis = bank.getClients();
		int num = bank.getNumberOfClients();
		
		for (int i = 0; i < num; i++) {
			clis[i].getClientSituation();
			Account[] accs = clis[i].getAccounts();
			int num1 = clis[i].getNumberOfAccounts();
			for (int j = 0; j < num1; j++) {
				System.out.println(j +" Maxium to withdraw: " + accs[j].maximumAmountToWithdraw());
			}
		}
	}
	public static void saveBank(Bank bank, String pathTo) throws SavingDataFailure{
		ObjectOutputStream ois;
		try {
			ois = new ObjectOutputStream(new FileOutputStream(pathTo));
			ois.writeObject(bank);
			ois.close();
		} catch (FileNotFoundException e) {
			throw new SavingDataFailure();
		} catch (IOException e) {
			throw new SavingDataFailure();
		}

	}
	public static Bank readBank(String pathFrom) throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(pathFrom));
		Bank bank = (Bank)ois.readObject();
		ois.close();
		return bank;
		
	}
}
